
import Vue from 'vue'
import configService from '@/common/service/config.service.js';
import vuex from '@/store';
import {ACCESS_TOKEN} from '@/common/util/constants.js'
const BASE_URL = configService.apiUrl
let throttleBool = false
export default async (params) => {
	
	if(!params.noLoading){
		// 加载中
		uni.showLoading({
		    title: '加载中'
		})
	}
  
	let defaultData ={}
	// if(params.isOpenId){
	// 	defaultData.openId = uni.getStorageSync('openId')
	// }
	Object.assign(defaultData,params.data)

	let count = 0
    return new Promise(async(resolve, reject) => {
		
		// // #ifdef MP-WEIXIN
		// if(params.isOpenId && !defaultData.openId){
		// 	let code = ''
		// 	await getwxCode().then( res=>{
		// 		code = res
		// 	})
		// 	await getOpenidApi({
		// 		js_code : code
		// 	}).then( res=>{
		// 		defaultData.openId = res.openId 
		// 		uni.setStorageSync('openId',res.openId )
		// 	})
		// }
		// // #endif
		
		let header = {
			'Content-Type':  'application/json',
			'X-Access-Token' : uni.getStorageSync(ACCESS_TOKEN)
			// 'Content-Type': 'application/x-www-form-urlencoded' ,
		}
		
		// if(token){
		// 	header.token = token
		// }
		
        uni.request({
            ...params,
            url: BASE_URL + params.url,
            method: params.method || 'POST',
            // data: params.data || {},
            data: defaultData,
            dataType: "json",
            header,
            success(res) {
				uni.hideLoading()
				if(res.data.message=='token失效，请重新登录'){
					once(()=>{
						uni.showToast({
						    title: '登录失效，正在重新登录',
						    duration: 3000,
						    icon: 'none',
							success: () => {
							}
						});
						setTimeout(()=>{
							uni.reLaunch({
								url: '/pages/index/index'
							})
						},1500)
					})()
				}else if( res.data.result == '1'){
					return resolve(res.data)
				}else{
					let title
					try{
					title = res.data.message ? res.data.message : res.data.msg
					}catch(e){
						//TODO handle the exception
					}
					title ? title : '服务器错误'
					uni.showToast({
					    title,
					    duration: 3000,
					    icon: 'none',
						success: () => {
							reject(res.data)
						}
					});
				}
				
            },
            fail(err) {
				uni.hideLoading()
                uni.showToast({
                    title: '服务器错误',
                    duration: 3000,
                    icon: 'none',
					success: ()=>{
							reject(err)
					}
                });
				
            },
            complete() {
               
            }
        })
    })
}

function getwxCode() {
	return new Promise((resolve, reject)=>{
		wx.login({
			success(res) {
				let code = res.code
				resolve(code)
			},
		})
	})
}

function once(fn) {
    let caller = true;
    return function() {
        if(caller) {
            caller = false
            fn.apply(this, arguments)
        }
    }
    
}
